<template>
  <el-dialog
    :title="formData.id?'编辑页面':'添加页面'"
    :visible="showDialog"
    width="80%"
    @close="closeFn"
  >
    <el-form ref="form" label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <template>
          <vue-editor v-model="formData.content" />
        </template>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addPages, getPagesDetailsId, updatePages } from '@/api/pages'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { mix: 1, max: 10, message: '标题长度必须是1-10个字符长度' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { mix: 1, max: 500, message: '内容长度必须是1-500个字符长度' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
      this.formData = {
        title: '',
        content: ''
      }
      this.$refs.form.resetFields()
    },
    // 点击确认触发的事件
    async confirmFn() {
      try {
        await this.$refs.form.validate()
        // 添加加载中效果
        const loading = this.$loading({
          lock: true,
          text: '拼命加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if (this.formData.id) {
        // 编辑
          await updatePages(this.formData)
          this.$message.success('编辑页面成功！')
        } else {
        // 添加
          await addPages(this.formData)
          this.$message.success('添加页面成功！')
        }
        this.closeFn()
        // 子组件通知父组件更新浏览器上的值
        this.$emit('updateEvent')
        // 关闭加载中效果
        loading.close()
      } catch (error) {
        console.log('校验不通过')
      }
    },
    // 根据id获取页面详情
    async getPagesDetailsId(id) {
      this.formData = await getPagesDetailsId(id)
    }
  }
}
</script>

<style>

</style>
